package com.happyfamily.springboot.crowdsourcingplatform.service.pan.impl;

import com.happyfamily.springboot.crowdsourcingplatform.dao.weng.PermissionDao;
import com.happyfamily.springboot.crowdsourcingplatform.dto.LoginBackUser;
import com.happyfamily.springboot.crowdsourcingplatform.model.SysPermission;
import com.happyfamily.springboot.crowdsourcingplatform.model.SysUser;
import com.happyfamily.springboot.crowdsourcingplatform.service.pan.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * spring security登陆处理
 * 处理用户信息获取的逻辑
 * UserDetailsService的实现类
 *
 * @AUThor
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{

	@Autowired
	private UserService userService;
	@Autowired
	private PermissionDao permissionDao;

	/**
	 * 处理用户校验逻辑
	 *
	 * @param username
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
	{

		SysUser sysUser = userService.getUser(username);

		//如果用户为空
		if (sysUser == null)
		{
			//抛出一个异常
			throw new AuthenticationCredentialsNotFoundException("用户名不存在");
		}
		//如果用户状态为禁用状态
		else if (sysUser.getPid() == SysUser.Status.LOCKED)
		{
			throw new LockedException("用户被锁定,请联系管理员");
		}
		//如果用户状态为删除状态
		else if (sysUser.getPid() == SysUser.Status.DISABLED)
		{
			throw new DisabledException("用户已作废");
		}

		LoginBackUser loginBackUser = new LoginBackUser();

		BeanUtils.copyProperties(sysUser, loginBackUser);

		//根据用户id查询相关菜单
		List<SysPermission> permissions = permissionDao.listByUserId(sysUser.getUid());
		loginBackUser.setPermissions(permissions);

		//		UserDetails userDetails= User.withUsername(sysUser.getUaccount()).password(loginBackUser.getPassword()).authorities(permissions).build();
		//如果不为空构造一个认证user
		//		AnyUser user=new AnyUser();
		//		user.setId((long)u.getId());
		//		user.setBirthday(u.getBirthday());
		//		user.setEmail(u.getEmail());
		//		user.setName(u.getName());
		//		user.setNickname(u.getNickname());
		//		user.setPhone(u.getPhone());
		//		user.setPlace(u.getPlace());
		//		user.setRole(u.getRole());
		//		user.setSex(u.getSex());
		//		user.setStreet(u.getStreet());

		return loginBackUser;
	}

}
